package fr.nantes.univ.servlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import fr.nantes.univ.DAO.UserDAO;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		HttpSession session = request.getSession(true);
		
        if (user != null) {
        	session.setAttribute("id",user.getUserId());
        	session.setAttribute("email", user.getEmail());
            fr.nantes.univ.EntityBeans.User u = new fr.nantes.univ.EntityBeans.User();
            u.setId(user.getUserId());
            u.setEmail(user.getEmail());
            u.setNickName(user.getNickname());
            UserDAO.insert(u);
            session.setAttribute("user", u);
            response.sendRedirect("/dashboard");
        } else {
        	response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
        }
	}
	
	

}